from django.contrib.auth.signals import user_logged_in, user_logged_out
from rest_framework_simplejwt.tokens import RefreshToken


def jwt_login(request, user):
    request.user = user
    user_logged_in.send(sender=user.__class__, request=request, user=user)


def jwt_logout(request, refresh_token):
    """
    Remove the authenticated user's ID from the request and flush their session
    data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.

    # 退出登陆后禁用refresh_token
    try:
        token = RefreshToken(refresh_token)
        token.blacklist()
    except Exception:
        pass

    user = getattr(request, 'user', None)
    if not getattr(user, 'is_authenticated', True):
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)
    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()


